<?php

declare (strict_types=1);


namespace app\api\controller;

use addons\V2\admin\model\OrderTemporary;
use AliPay\App as AliPay;
use app\common\model\Logs;
use app\common\model\User;
use app\common\model\Remit as RemitModel;
use app\common\tool\joinpay\Pay;
use addons\Target\facade\Target;

/**
 * 支付回调
 */
class Callback extends Base
{
    public function alipayCallback()
    {
        try {
            $route = 'callback/alipayCallback.log';

            $pay = AliPay::instance(config('pay.alipay'));
            $data = $pay->notify();
//            Logs::write($route, json_encode($data));
            if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                // @todo 更新订单状态，支付完成
                $info = OrderTemporary::where('sn', $data['out_trade_no'])->findOrEmpty();
                if (!$info->isEmpty() && $info->getData('status') == 1) {
                    $user = \app\common\model\User::where('id', $info->uid)->find();
                    $result = OrderTemporary::operations($info, $user, 'alipay');
                    if ($result['code'] != -1) {
                        Logs::write($route, '成功，订单号:' . $info->sn);
                        return 'SUCCESS';
                    } else {
                        Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg'] . '回调验证失败:' . json_encode($data));
                    }
                }
            } else {
                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败:' . json_encode($data));
            }
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());
        }
        return 'fail';
    }

    public function alipayOrder()
    {
        try {
            $route = 'callback/alipayOrder.log';
            $data = $this->request->param();

            if ($data['r6_Status'] == 100) {
                if (Pay::verify($data)) {
                    $info = OrderTemporary::where('sn', $data['r2_OrderNo'])->findOrEmpty();
                    if (!$info->isEmpty() && $info->getData('status') == 1) {
                        $user = \app\common\model\User::where('id', $info->uid)->find();
                        $result = OrderTemporary::operations($info, $user, 'alipay');
                        if ($result['code'] != -1) {
                            Logs::write($route, '成功，订单号:' . $info->sn);
                            return 'SUCCESS';
                        } else {
                            Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg'] . '回调验证失败:' . json_encode($data));
                        }
                    }
                }
                // 返回接收成功的回复
                Logs::write($route, '订单支付成功');
            } else {
                Logs::write($route, '回调验证失败：' . json_encode($data));
            }

        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
        }
        return 'fail';
    }

    public function drawOrder()
    {
        try {
            $route = 'callback/drawOrder.log';
            $data = $this->request->param();
//            Logs::write($route, json_encode($data));
            if ($data['status'] == 205) {
                $info = \app\common\model\Draw::where('sn', $data['merchantOrderNo'])->findOrEmpty();
                if (!$info->isEmpty() && $info->getData('status') == 1) {
                    $info->status = 2;
                    $info->confirm_time = time();
                    $info->save();
                    Logs::write($route, '成功，订单号:' . $info->sn);
                    return json(['statusCode' => '2001', 'message' => '成功']);
                }
                // 返回接收成功的回复
                Logs::write($route, '验证失败');
            } else {
                $info = \app\common\model\Draw::where('sn', $data['merchantOrderNo'])->findOrEmpty();
                $info->reject_msg = $data['errorCodeDesc'];
                $info->status = 3;
                $info->confirm_time = time();
                Target::Account()->basics($info['uid'], $info->getData('account'), $info['money'], '提现驳回', '+')
                    ->createNormal();
                $info->save();
                Logs::write($route, '回调验证失败：' . json_encode($data));
            }

        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
        }
        return 'fail';
    }

    /**
     * @return string|void
     * 原点 2022年1月11日11:27:15 支付宝支付通用回调
     */
    public function aliPayRemit1()
    {
        try {

            $config = config('pay.alipay');
            $alipay = AliPay::instance($config);
            $route = 'callback/aliPayOrder.log';
            $result = $alipay->notify();

            if ($result) {
//                Logs::write($route, json_encode($result));
                if (in_array($result['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                    $info = RemitModel::where('sn', $result['out_trade_no'])->find();
                    if ($info && $info->pay_state != 2) {
                        $result = RemitModel::operate($info);
                        if ($result['code'] == 1) {
                            Logs::write($route, '成功，订单号:' . $info->sn);
                        } else {
                            Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                        }
                    } else {
                        Logs::write($route, '未查询到订单');
                    }
                }
                return 'success';
            } else {
                return 'fail';
            }
        } catch (\Exception $e) {
            return 'fail';
        }
    }

    public function aliPayRemit()
    {
        try {

            $route = 'callback/alipayOrder.log';
            $data = $this->request->param();
            if ($data['r6_Status'] == 100) {
//                Logs::write($route, json_encode($result));
                if (Pay::verify($data)) {
                    $info = RemitModel::where('sn', $data['r2_OrderNo'])->find();
                    if ($info && $info->pay_state != 2) {
                        $result = RemitModel::operation($info);
                        if ($result['code'] == 1) {
                            Logs::write($route, '成功，订单号:' . $info->sn);
                        } else {
                            Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                        }
                    } else {
                        Logs::write($route, '未查询到订单');
                    }
                }
                return 'success';
            } else {
                return 'fail';
            }
        } catch (\Exception $e) {
            return 'fail';
        }
    }

    /**
     * @return string
     * 原点 2022年1月11日11:32:49 微信支付通用回调
     */
    public function weChatRemit()
    {
        try {
            $config = config('pay.wechat');
            $wechat = \WeChat\Pay::instance($config);
            $data = $wechat->getNotify();
            $route = 'callback/weChatOrder.log';
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                $info = RemitModel::where('sn', $data['out_trade_no'])->find();
                if ($info && $info->pay_state != 2) {
                    $result = RemitModel::operation($info);
                    if ($result['code'] == 1) {
                        Logs::write($route, '成功，订单号:' . $info->sn);
                    } else {
                        Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                    }
                } else {
                    Logs::write($route, '未查询到订单');
                }
            } else {
                Logs::write($route, '非支付回调');
                exit();
            }
            return 'success';
        } catch (\Exception $e) {
            return 'fail';
        }
    }

}